package com.zjzywl.iotSendthings.controller;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import com.zjzywl.iotSendthings.configuration.AppConfig;
import com.zjzywl.iotSendthings.util.WebResult;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

@Controller
public class PoliceLoginController extends HttpServlet {
    @Autowired
    private AppConfig config;
    @Value("${app.serverUrl}")
    private String url;

    // 警员登陆接口
    @RequestMapping(value = "/policeLogin")
    @ResponseBody
    public WebResult doGet(Model model, HttpServletResponse response, HttpServletRequest request) throws Exception {
        response.setContentType("text/json; charset=UTF-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");


        RestTemplate config = new RestTemplate();
        System.out.println("警官登录链接" + url + "/p2/MJXX.jsp?USR=" + username + "&PWD=" + password);
        config.exchange(url + "/p2/MJXX.jsp?USR=" + username + "&PWD=" + password, HttpMethod.GET, null, String.class);
        ResponseEntity<String> exchange = config.exchange(url + "/p2/MJXX.jsp?USR=" + username + "&PWD=" + password,
                HttpMethod.GET, null, String.class);
        Map<String, String> map = new HashMap<>();
        System.out.println(exchange.getBody().length());

        if (exchange.getBody().length() > 150) {
            try {
                // 创建session对象
                HttpSession session = request.getSession(true);

                // 创建xml解析对象
                SAXReader reader = new SAXReader();
                // 定义一个文档
                Document document = null;
                // 将字符串转换为
                document = reader.read(new ByteArrayInputStream(exchange.getBody().getBytes("GBK")));
                // 得到xml的根节点(message)
                Element bookStore = document.getRootElement();
                Element record = bookStore.element("record");
                Element jbxx = record.element("jbxx");
                // 通过element对象的elementIterator方法获取迭代器
                Iterator it = record.elementIterator();
                // 遍历迭代器，获取根节点中的信息（书籍）
                while (it.hasNext()) {
                    //开始遍历
                    Element book = (Element) it.next();
                    // 获取属性名以及 属性值
                    Iterator itt = book.elementIterator();
                    while (itt.hasNext()) {
                        Element bookChild = (Element) itt.next();
                        map.put(bookChild.getName(), bookChild.getStringValue().trim().substring(2, bookChild.getStringValue().trim().length()));
                    }
                    // 把用户数据保存在session域对象中
                    session.setAttribute("username", map.get("xm"));
                    session.setMaxInactiveInterval(-1);// 设置单位为秒，设置为-1永不过期
                }
            } catch (DocumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return WebResult.OK(map);

        } else {
            return WebResult.FAIL("用户不存在");
        }

    }

    // // 本地測試：警员登陆接口
    // @RequestMapping(value = "/policeLogin")
    // @ResponseBody
    // public WebResult doGet(Model model, HttpServletResponse response,
    // HttpServletRequest request) throws Exception {
    // response.setContentType("text/json; charset=UTF-8");
    // String username = request.getParameter("username");
    // String password = request.getParameter("password");
    // // 创建session对象
    // HttpSession session = request.getSession(true);
    // // 把用户数据保存在session域对象中
    // session.setAttribute("username", "1");
    // session.setMaxInactiveInterval(-1);// 设置单位为秒，设置为-1永不过期
    // Object attribute = session.getAttribute("username");
    // System.out.println("session:" + attribute);
    // return WebResult.OK();
    //
    // }

    // 查询在押人员余额
    @RequestMapping(value = "/findMoney")
    @ResponseBody
    public WebResult findMoney(HttpServletResponse response, HttpServletRequest request) throws Exception {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setContentType("text/json; charset=UTF-8");
        String rybh = request.getParameter("rybh");
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(2000);
        requestFactory.setReadTimeout(2000);
        RestTemplate config = new RestTemplate(requestFactory);
        ResponseEntity<Object> exchange = config.exchange(
                "http://10.120.135.214:8180/jc/prisonerAccount/findByNumber?number=" + rybh, HttpMethod.GET, null,
                Object.class);
        return WebResult.OK(exchange);

    }

    // 警员账号失效验证
    @RequestMapping(value = "/user/out")
    @ResponseBody
    public void UserNameOut(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String username = (String) request.getSession().getAttribute("username");
        System.out.println(username);
        if (username == null) {
            response.sendError(403, "Invalid landing, please re-login");
        }

    }
}
